﻿using WebApiClient.Attributes;
using WebApiClient;
using static System.Net.WebRequestMethods;
using System.Net.Http;
using HtmlAgilityPack;
using Newtonsoft.Json;
using QQRobot.Services.Models.Response;
using QQRobot.Services.Models.Request;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace QQRobot.Services
{
    public class BaiduAPI
    {


        #region 百度热搜
        /// <summary>
        /// 百度热搜
        /// </summary>
        /// <returns></returns>
        public static async Task<BaiduHotSearchResponse> GetBaiduHotSearchAsync()
        {

            var api = HttpApi.Create<IBaiduAPI>();
            var htmlContent = await api.GetBaiduHotSearchAsync("realtime");
            string nodeContent = ExtractNodeContent(htmlContent, "sanRoot");
            var jsonData = ExtractJsonFromComment(nodeContent);
            BaiduHotSearchResponse response = JsonConvert.DeserializeObject<BaiduHotSearchResponse>(jsonData);
            return response;
        }
        static string ExtractNodeContent(string htmlContent, string nodeId)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlContent);

            HtmlNode node = doc.GetElementbyId(nodeId);
            return node?.InnerHtml;
        }

        static string ExtractJsonFromComment(string content)
        {
            if (string.IsNullOrEmpty(content))
                return null;

            int startIndex = content.IndexOf("<!--s-data:");
            if (startIndex == -1)
                return null;

            startIndex += "<!--s-data:".Length;
            int endIndex = content.IndexOf("-->", startIndex);
            if (endIndex == -1)
                return null;

            string jsonData = content.Substring(startIndex, endIndex - startIndex).Trim();
            return jsonData;
        }
        #endregion

        #region 百度翻译
        /// <summary>
        /// 参考文档 <see cref="https://api.fanyi.baidu.com/doc/21"/>
        /// </summary>
        /// 


        private const string translateAPPID = "20201102000605871";
        private const string translateSecretKey = "A5q9LtPQ_DS5ecZ1He4k";

        public static async Task<BaiduTranslateResponse> GetBaiduTranslateAsync(string query)
        {
            var api = HttpApi.Create<IBaiduAPI>();
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            // 源语言
            string from = "zh";
            // 目标语言
            string to = "en";
            string sign = EncryptString(translateAPPID + query + salt + translateSecretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(query);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + translateAPPID;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            return await api.GetBaiduTranslateAsync(url);
        }

        // 计算MD5值
        public static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串，
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }

        #endregion
    }




    /// <summary>
    /// 
    /// </summary>
    //[HttpHost("http://api.fanyi.baidu.com")]
    public interface IBaiduAPI : IHttpApi
    {
        /// <summary>
        /// 获取百度实时热搜
        /// </summary>
        /// <returns></returns>
        [HttpGet("https://top.baidu.com/board")]
        ITask<string> GetBaiduHotSearchAsync(string tab);

      
        [HttpGet]
        [Header("ContentType", "text/html;charset=UTF-8")]
        [JsonReturn]
        ITask<BaiduTranslateResponse> GetBaiduTranslateAsync([Uri] string url);
    }



}

